package com.syy.framework.web.service;

import com.syy.common.annotation.Mobile;
import com.syy.common.constant.CacheConstants;
import com.syy.common.constant.Constants;
import com.syy.common.constant.UserConstants;
import com.syy.common.core.domain.entity.SysUser;
import com.syy.common.core.domain.model.LoginUser;
import com.syy.common.core.redis.RedisCache;
import com.syy.common.exception.ServiceException;
import com.syy.common.exception.user.BlackListException;
import com.syy.common.exception.user.CaptchaExpireException;
import com.syy.common.exception.user.UserNotExistsException;
import com.syy.common.exception.user.UserPasswordNotMatchException;
import com.syy.common.utils.MessageUtils;
import com.syy.common.utils.StringUtils;
import com.syy.common.utils.ip.IpUtils;
import com.syy.framework.manager.AsyncManager;
import com.syy.framework.manager.factory.AsyncFactory;
import com.syy.framework.security.context.AuthenticationContextHolder;
import com.syy.system.api.SmsCodeApi;
import com.syy.system.domain.AliyunSmsProperties;
import com.syy.system.domain.dto.SmsCodeSendReqDTO;
import com.syy.system.domain.vo.AuthSmsSendReqVO;
import com.syy.system.service.AuthConvert;
import com.syy.system.service.ISysConfigService;
import com.syy.system.service.ISysUserService;
import com.syy.system.service.impl.SysUserServiceImpl;
import com.syy.utils.DateUtils;
import com.syy.utils.Threads;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.syy.common.exception.ServiceExceptionUtil.exception;
import static com.syy.common.utils.ServletUtils.getClientIP;

/**
 * 登录校验方法
 *
 * @author 地理信息中心
 */
@Component
public class SysLoginService {

    private final AliyunSmsProperties smsProperties;

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private SmsCodeApi smsCodeApi;

    @Autowired(required=true)
    private AuthConvert authConvert;
    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;

    private static final Logger logger = LoggerFactory.getLogger(SysLoginService.class);

    public SysLoginService(AliyunSmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */

    public String login(String username, String password,String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }catch (Exception e) {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
        }
    }
        /**
         * 登录前置校验
         * @param username 用户名
         * @param password 用户密码
         */
        public void loginPreCheck(String username, String password){
            // 用户名或密码为空 错误
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
                throw new UserNotExistsException();
            }
            // 密码如果不在指定范围内 错误
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            // 用户名不在指定范围内 错误
            if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            // IP黑名单校验
            String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
            if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
                throw new BlackListException();
            }
        }
    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /*
    *
    * 发送验证码
    */
    public void sendSmsCode(AuthSmsSendReqVO reqVO) {
        // 发送验证码
        System.out.println("reqVO = " + reqVO);
        try {
            SmsCodeSendReqDTO convert = authConvert.convert(reqVO);
            convert.setCreateIp(getClientIP());
            smsCodeApi.sendSmsCode(convert);
        } catch (Throwable t) {
            System.err.println("【ERROR】转换失败！");
            t.printStackTrace();
        }
            // 如果是重置密码场景，需要校验图形验证码是否正确
          /*  if (Objects.equals(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene(), reqVO.getScene())) {
                ResponseModel response = doValidateCaptcha(reqVO);
                if (!response.isSuccess()) {
                    throw exception(AUTH_REGISTER_CAPTCHA_CODE_ERROR, response.getRepMsg());
                }
            }*/

            /*登录场景，验证是否存在*/
            /*if (userService.getUserByMobile(reqVO.getMobile()) == null) {
                throw exception(AUTH_MOBILE_NOT_EXISTS);
            }*/
    }

    /**
     * 阿里云发送登录验证码
     * @param phonenumber 已验证的手机号
     * @return 发送结果
     * @throws ServiceException 包含各种业务异常（验证码已发送、手机未注册等）
     */
    public Boolean sendLoginAliyunCode(@Mobile String phonenumber) {
        final String codeKey = CacheConstants.CAPTCHA_CODE_KEY + phonenumber;

        // 防刷校验
        if (hasSentCodeRecently(codeKey)) {
            logger.warn("验证码发送频繁，手机号：{}", phonenumber);
            throw new ServiceException("验证码已发送，请勿重复发送");
        }
        // 用户存在性校验
        SysUser sysUser = userService.selectUserByPhone(phonenumber);
        if (sysUser == null) {
            logger.warn("未注册手机号尝试发送验证码：{}", phonenumber);
            throw new UserNotExistsException();
        }

        try {
            String code = generateSecureVerificationCode();
            // 存储验证码
            redisCache.setCacheObject(codeKey, code, smsProperties.getCodeExpireMinutes(), TimeUnit.MINUTES);
            // 异步发送短信
            asyncSendVerificationCode(phonenumber, code);
            logger.info("验证码发送成功，手机号：{}", phonenumber);
            return true;
        } catch (Exception e) {
            logger.error("验证码发送异常，手机号：{}，错误：{}", phonenumber, e.getMessage(), e);
            throw new ServiceException("验证码发送失败，请稍后重试");
        }
    }

    private void asyncSendVerificationCode(String phone, String code) {
        //异步去执行任务
        AsyncManager.me().execute(AsyncFactory.buildSmsSendTask(phone,code));
    }


    /**
     * 检查是否已发送过验证码（未过期）
     * @param codeKey Redis key（如：CAPTCHA_CODE_KEY + 手机号）
     * @return true=已发送且未过期，false=未发送或已过期
     */
    private boolean hasSentCodeRecently(String codeKey) {
        try {
            // 1. 检查Redis中是否存在该key
            Boolean exists = redisCache.hasKey(codeKey);
            return Boolean.TRUE.equals(exists);
        } catch (Exception e) {
            logger.error("检查验证码是否存在异常，key: {}, 错误: {}", codeKey, e.getMessage(), e);
            // 如果Redis访问异常，保守起见返回true（避免刷接口）
            return true;
        }
    }

    /**
     * 生成6位数字验证码（生产级优化）
     *
     * 优化点：
     * 1. 使用静态SecureRandom实例避免重复初始化开销
     * 2. 添加验证码黑名单过滤（如避免888888等简单密码）
     * 3. 增加重试机制防止生成无效验证码
     * 4. 性能优化（使用预分配char数组代替String.format）
     * 5. 添加日志记录用于安全审计
     */
    public String generateSecureVerificationCode() {
        // 使用静态的SecureRandom实例（线程安全）
        final SecureRandom SECURE_RANDOM = new SecureRandom();

        // 常见简单密码黑名单
        final Set<String> BLACKLIST = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
                "000000", "111111", "222222", "333333",
                "444444", "555555", "666666", "777777",
                "888888", "999999", "123456", "654321"
        )));

        // 最大重试次数
        final int MAX_RETRY = 3;

        int retryCount = 0;
        char[] codeChars = new char[6];

        while (retryCount++ < MAX_RETRY) {
            // 生成6位数字
            int num = SECURE_RANDOM.nextInt(1_000_000);

            // 转换为char数组（比String.format性能更好）
            for (int i = 5; i >= 0; i--) {
                codeChars[i] = (char) ('0' + num % 10);
                num /= 10;
            }

            String code = new String(codeChars);

            // 检查是否在黑名单中
            if (!BLACKLIST.contains(code)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Generated verification code: {}", code);
                }
                return code;
            }

            logger.warn("Generated blacklisted code, retrying...");
        }
        // 如果多次生成都在黑名单中，fallback到安全随机生成
        return String.format("%06d", SECURE_RANDOM.nextInt(900000) + 100000);
    }
}
